#!/bin/bash

# 颜色定义
GREEN="\033[0;32m"
BLUE="\033[0;34m"
YELLOW="\033[0;33m"
RED="\033[0;31m"
NC="\033[0m" # No Color

# 打印带颜色的信息
info() {
  echo -e "${BLUE}[INFO]${NC} $1"
}

success() {
  echo -e "${GREEN}[SUCCESS]${NC} $1"
}

warning() {
  echo -e "${YELLOW}[WARNING]${NC} $1"
}

error() {
  echo -e "${RED}[ERROR]${NC} $1"
  exit 1
}

# 检查项目路径
if [ -z "$1" ]; then
  error "请提供项目路径作为参数"
fi

PROJECT_PATH="$1"

if [ ! -d "$PROJECT_PATH" ]; then
  error "项目路径 $PROJECT_PATH 不存在"
fi

cd "$PROJECT_PATH" || error "无法进入项目目录"

info "开始验证项目: $PROJECT_PATH"

# 检查必要文件和目录是否存在
check_files() {
  local files=(
    "vite.config.ts"
    "pages.config.ts"
    "manifest.config.ts"
    "uno.config.ts"
    "src/main.ts"
    "src/App.vue"
    "src/pages/index/index.vue"
    "src/manifest.json"
    ".eslintrc.cjs"
    ".prettierrc.cjs"
    ".stylelintrc.cjs"
    ".vscode/settings.json"
  )

  local dirs=(
    "src/api"
    "src/components"
    "src/hooks"
    "src/interceptors"
    "src/layouts"
    "src/pages"
    "src/static"
    "src/stores"
    "src/style"
    "src/types"
    "src/utils"
    "env"
    ".vscode"
  )

  info "检查必要文件是否存在"
  for file in "${files[@]}"; do
    if [ ! -f "$file" ]; then
      warning "文件不存在: $file"
    else
      echo "✓ $file"
    fi
  done

  info "检查必要目录是否存在"
  for dir in "${dirs[@]}"; do
    if [ ! -d "$dir" ]; then
      warning "目录不存在: $dir"
    else
      echo "✓ $dir"
    fi
  done
}

# 检查依赖是否安装
check_dependencies() {
  info "检查依赖是否安装"
  local deps=(
    "@dcloudio/vite-plugin-uni"
    "@uni-helper/vite-plugin-uni-pages"
    "@uni-helper/vite-plugin-uni-platform"
    "@uni-helper/vite-plugin-uni-layouts"
    "@uni-helper/vite-plugin-uni-manifest"
    "unplugin-auto-import"
    "vite-plugin-restart"
    "prettier"
    "eslint"
    "stylelint"
    "unocss"
    "pinia"
    "pinia-plugin-persistedstate"
  )

  if [ ! -f "package.json" ]; then
    error "package.json 不存在"
  fi

  for dep in "${deps[@]}"; do
    if ! grep -q "\"$dep\"" package.json; then
      warning "依赖未安装: $dep"
    else
      echo "✓ $dep"
    fi
  done
}

# 尝试构建项目
build_project() {
  info "尝试构建项目"
  if ! pnpm build; then
    warning "项目构建失败"
    return 1
  fi
  success "项目构建成功"
  return 0
}

# 运行检查
check_files
check_dependencies

# 询问是否尝试构建项目
read -p "是否尝试构建项目? (y/n): " BUILD_PROJECT
if [ "$BUILD_PROJECT" = "y" ]; then
  build_project
fi

success "项目验证完成"
